package org.xq.shop.maxaishop.auth;

import com.alibaba.fastjson.JSON;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.xq.shop.maxaishop.entity.XqAdmin;
import org.xq.shop.maxaishop.util.JwtUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
/**
 * 自定义验证Token过滤器，集成BasicAuthenticationFilter过滤器
 */
public class TokenVerifyFilter extends BasicAuthenticationFilter {
    private RsaKeyProperties prop;//公钥、私钥属性对象
    public TokenVerifyFilter(AuthenticationManager authenticationManager, RsaKeyProperties prop) {
        super(authenticationManager);
        this.prop = prop;
    }
    /**
     * 验证token方法
     */
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response
            , FilterChain chain) throws IOException, ServletException {
        String header = request.getHeader("Authorization");
        //如果请求头里不包含Token信息,返回请求被拒绝状态
        if (header == null) {
            //如果携带错误的token，则给用户提示请登录！
            chain.doFilter(request, response);

        } else {
            //如果没有携带Bearer 返回错误
            if (!header.startsWith("Bearer")) {
                response.setContentType("application/json;charset=utf-8");
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);//SC_FORBIDDEN  403 请求拒绝状态
                PrintWriter out = response.getWriter();
                Map resultMap = new HashMap();
                resultMap.put("code", HttpServletResponse.SC_FORBIDDEN);
                resultMap.put("msg", "请登录！");
                out.write(JSON.toJSONString(resultMap));
                out.flush();
                out.close();
            } else {
                //如果携带了正确格式的token要先得到token
                String token = header.replace("Bearer ", "");
                //通过公钥解析token，并返回载荷对象
                Payload<XqAdmin> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), XqAdmin.class);
                XqAdmin user = payload.getUserInfo();

                if (user != null) {
                    //带用户名和密码以及权限的Authentication
                    UsernamePasswordAuthenticationToken authResult = new UsernamePasswordAuthenticationToken(
                            user.getUsername(),     //用户信息
                            null,
                            user.getAuthorities()); //权限信息
                    //将授权对象authResult加入Security容器中
                    SecurityContextHolder.getContext().setAuthentication(authResult);

                    chain.doFilter(request, response);
                }
            }
        }
    }
}
